//
//  WBMainViewController.swift
//  Weibo
//
//  Created by 伏文东 on 2018/1/22.
//  Copyright © 2018年 伏文东. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {
    
    /// 定时器
    private var timer: Timer?
    
    // 撰写(+)按钮
    @objc private lazy var composeButton: UIButton = UIButton.cz_imageButton(
        "tabbar_compose_icon_add",
        backgroundImageName: "tabbar_compose_button")
    // MARK: 按钮监听方法
    // FIXME: 没有实现
    @objc private func composeStatus() {
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.green
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
    }
    // MARK: 系统回调
    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        
        setupNewfeatureViews()
        
        // 设置代理
        delegate = self
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    /**
     protrait: 竖屏, 肖像
     landscape：横屏， 风景
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait }
    
    // MARK:- 监听方法
    @objc private func userLogin(n: Notification) {
        print("用户登录通知\(n)")
        
        var when = DispatchTime.now()
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            self.present(nav, animated: true, completion: nil)
        }
    }
    
}
// MARK:- 遵守UITabBarControllerDelegate协议
extension WBMainViewController: UITabBarControllerDelegate {
    /// 将要选择 tabbarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到 目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到控制器\(viewController)")
        
        // 1> 获取控制器数组索引
        let index = (childViewControllers as NSArray).index(of: viewController)
        // 2>  判断当前索引是首页， 同时点击 index 也是首页 ，重复点击首页按钮
        if selectedIndex == 0 && index == selectedIndex {
            // 让表格滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
            
            // 清除tabItem 的badgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK:- 时钟相关方法
extension WBMainViewController {
    func setupTimer()  {
        timer = Timer.scheduledTimer(timeInterval: 66.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    /// 触发时钟
    @objc private func updateTimer() {
        guard WBNetworkManager.shared.userLogon else { return }
        
        WBNetworkManager.shared.unreadCount { (count) in
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            // 设置 applicationIconBadgeNumber 从iOS 8.0 之后要用户授权才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

extension WBMainViewController {
    /// 设置新特性视图
    private func setupNewfeatureViews()  {
        
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        // 检查版本是否更新
        
        //  如果更新， 显示新特性 ， 否则显示欢迎
        let v = isNewVersion ? WBNewFeature.newFeature() : WBWelcomeView.welcomeView()
        
        v.frame = view.bounds
        
        view.addSubview(v)
    }
    // 新版本判断逻辑
    private var isNewVersion: Bool {
        
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        return currentVersion != sandboxVersion
//        return currentVersion == sandboxVersion
    }
}

extension WBMainViewController {
    // 设置(+)撰写按钮
    private func setupComposeButton() {
        tabBar.addSubview(composeButton)
        let count = CGFloat(childViewControllers.count)
        // 向内缩颈防止穿帮
        let w = tabBar.bounds.width / count
         composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    private func setupChildControllers() {
        
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载 data
        var data = NSData(contentsOfFile: jsonPath)
        
        if data  == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]] else { return }
        
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict))
        }
        
        viewControllers = arrayM
    }
    
    /// 使用字典创建一个自控制器
    ///
    /// - Parameter dict: 信息字典
    /// - Returns: 自控制器
    private func controller(_ dict: [String: Any]) -> UIViewController {
        
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String: String]
            else { return UIViewController() }
        let vc = cls.init()
        vc.title = title
        
        //设置控制器的访客信息字典
        vc.visitorDictoinaryInfo = visitorDict
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        
        // 设置tabbar的标题字体
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.orange], for: .highlighted)
        let nav = WBNaviViewController(rootViewController: vc)
        return nav
    }
    
    
}





























